<template>
  <el-form
    label-width="100px"
    :model="skuInfo"
    ref="skuFormRef"
    :rules="skuRules"
  >
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        class="mx-4"
        style="width: 100%"
        :min="1"
        :max="10"
        controls-position="right"
        v-model="skuInfo.price"
      />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="10"
        controls-position="right"
        v-model="skuInfo.weight"
      />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
          v-for="(attr, index) in attrList"
          :key="attr.id"
        >
          <el-form-item :label="attr.attrName">
            <el-select
              v-model="skuInfo.skuAttrValueList[index]"
              @change="clearAttrRules"
            >
              <el-option
                :label="valList.valueName"
                :value="`${attrList.id}:${attr.attrName}:${valList.id}:${valList.valueName}`"
                v-for="valList in attr.attrValueList"
                :key="valList.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
          v-for="(saleAttrList, index) in spuSaleAttrList"
          :key="saleAttrList.id"
        >
          <el-form-item :label="saleAttrList.saleAttrName">
            <el-select
              v-model="skuInfo.skuSaleAttrValueList[index]"
              @change="clearSaleAttrRules"
            >
              <el-option
                :value="`${saleAttrList.id}:${saleAttrList.saleAttrName}:${spuSaleAttrValueList.id}:${spuSaleAttrValueList.saleAttrValueName}`"
                :label="spuSaleAttrValueList.saleAttrValueName"
                v-for="spuSaleAttrValueList in saleAttrList.spuSaleAttrValueList"
                :key="spuSaleAttrValueList.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        border
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.imgUrl"
              :alt="row.imgName"
          /></template>
        </el-table-column>
        <el-table-column label="图片名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              v-if="row.isDefault === '0'"
              @click="setDefaultImage(row)"
              >设置为默认图片</el-button
            >
            <el-button type="success" v-else>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm(skuFormRef)">保存</el-button>
      <el-button @click="toSpuList">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SkuForm",
}
</script>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu"
import { reqGetAttrListDataByCategory3Id } from "@/api/product/attr"
import { useCategoryListStore } from "@/stores/categoryList"
import type { FormInstance, FormRules } from "element-plus"
import { reqSaveSkuInfo } from "@/api/product/sku"
import { ElMessage } from "element-plus"
const emits = defineEmits(["changeScene"]) // 接收自定义事件
const props = defineProps(["currentSpuInfo"])
const categoryStore = useCategoryListStore()

const spuImageList = ref<any>([]) // 图片列表
const spuSaleAttrList = ref<any>([]) // spu基础属性列表
const attrList = ref<any>([]) // 平台属性列表
const skuFormRef = ref<FormInstance>()
const skuInfo = reactive({
  skuName: "", // spu名字
  price: "", // 价格
  weight: "", // 重量
  skuDesc: "", // 描述
  skuDefaultImg: "", // 默认图片
  skuAttrValueList: [], // 平台属性
  skuImageList: [], // 图片列表
  skuSaleAttrValueList: [], // 销售属性列表
})

// 获取页面中一开始就要渲染的数据
onMounted(async () => {
  const supId = props.currentSpuInfo.id
  const [resSpuImageList, resSpuSaleAttrList, resAttrList] =
    await Promise.allSettled([
      reqGetSpuImageList(supId),
      reqGetSpuSaleAttrList(supId),
      reqGetAttrListDataByCategory3Id({
        category1Id: categoryStore.category1Id as number,
        category2Id: categoryStore.category2Id as number,
        category3Id: categoryStore.category3Id as number,
      }),
    ])
  console.log(resSpuImageList, resSpuSaleAttrList, resAttrList)
  if (resSpuImageList?.status === "fulfilled") {
    spuImageList.value = resSpuImageList.value.map((item) => {
      return {
        ...item,
        isDefault: "0", // 0表示正常,1表示默认项
      }
    })
  }
  if (resSpuSaleAttrList?.status === "fulfilled") {
    spuSaleAttrList.value = resSpuSaleAttrList.value
  }
  if (resAttrList?.status === "fulfilled") {
    attrList.value = resAttrList.value
  }
})
// 当选择图片的时候
const handleSelectionChange = (val) => {
  // console.log(val)
  skuInfo.skuImageList = val
}
// 设置默认图片
const setDefaultImage = (row) => {
  // 进行排他,现将之前的设置为正常
  spuImageList.value.forEach((item) => {
    item.isDefault = "0"
  })
  // 将当前被点击的设置为默认选项
  row.isDefault = "1"

  // 将当前的默认选项收集起来
  skuInfo.skuDefaultImg = row.imgUrl
}
// 书写一个图片的自定义校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  console.log("rule", rule, value, callback)
  if (value.length === 0) {
    callback("请至少选择一张图片...")
    return
  }
  if (!value.find((item) => item.isDefault === "1")) {
    callback("请选择默认图片...")
    return
  }
  callback() // 什么参数都不写，表示放行
}
// 定义校验规则
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入sku名称", trigger: "blur" },
    { min: 1, max: 10, message: "长度在1到10之间", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入sku描述", trigger: "blur" }],
  skuAttrValueList: [
    // 平台属性校验规则
    {
      required: true,
      message: "请至少选择一个平台属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: "请至少选择一个销售属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuImageList: [
    { required: true, validator: skuImageListValidate, trigger: "change" },
  ],
})
// 添加skuInfo
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.spuId = props.currentSpuInfo.id
      skuInfo.category3Id = props.currentSpuInfo.category3Id
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [attrId, attrName, valueId, valueName] = item.split(":")
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          }
        })
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
            item.split(":")
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          }
        })
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success("添加sku数据成功...")
      emits("changeScene", 1)
    } else {
      console.log("error submit!", fields)
    }
  })
}
// 清空平台属性的校验规则
const clearAttrRules = () => {
  skuFormRef.value?.clearValidate(["skuAttrValueList"])
}
// 清空销售属性的校验规则
const clearSaleAttrRules = () => {
  console.log("事件触发...aaaa")
  skuFormRef.value?.clearValidate(["skuSaleAttrValueList"])
}
// 单击取消时跳转回SpuList页面
const toSpuList = () => {
  emits("changeScene", 1)
}
</script>

<style></style>
